package com.ly.demo.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;

/**
 * @Author liuyang
 * @Date 2024/9/5 上午11:18
 **/
public class ImageMergeUtil {
    /**
     * 合并图片并返回合并后的Base64编码字符串
     *
     * @param base64Images List<String>，包含多个Base64编码的图片字符串
     * @return 合并后的图片的Base64编码字符串
     */
    public static String mergeImagesToBase64(List<String> base64Images) throws IOException {
        if (base64Images == null || base64Images.isEmpty()) {
            throw new IllegalArgumentException("图片列表不能为空");
        }

        // 解码Base64字符串为BufferedImage
        BufferedImage[] images = new BufferedImage[base64Images.size()];
        int totalHeight = 0;
        int maxWidth = 0;

        for (int i = 0; i < base64Images.size(); i++) {
            images[i] = decodeBase64ToImage(base64Images.get(i));
            // 计算总高度和最大宽度
            totalHeight += images[i].getHeight();
            maxWidth = Math.max(maxWidth, images[i].getWidth());
        }

        // 创建合并后的BufferedImage
        BufferedImage mergedImage = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = mergedImage.createGraphics();

        // 将每张图片绘制到合并图片上
        int currentHeight = 0;
        for (BufferedImage image : images) {
            g2d.drawImage(image, 0, currentHeight, null);
            currentHeight += image.getHeight();  // 累加高度
        }

        g2d.dispose();  // 释放资源

        // 将合并后的图片编码为Base64字符串
        return encodeImageToBase64(mergedImage, "png");
    }

    // 将 Base64 字符串解码为 BufferedImage
    private static BufferedImage decodeBase64ToImage(String base64Str) throws IOException {
        // 去除 Base64 前缀（如果有的话）
        if (base64Str.contains(",")) {
            base64Str = base64Str.split(",")[1];
        }
        byte[] imageBytes = Base64.getDecoder().decode(base64Str);
        ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
        return ImageIO.read(bais);
    }

    // 将 BufferedImage 编码为 Base64 字符串
    private static String encodeImageToBase64(BufferedImage image, String format) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, format, baos);
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }
}
